<template>
  <div>
    <div class="mynavContaier">
      <mynav></mynav>
    </div>
    <div class="container kline">

     <center-info></center-info>


      <el-row style="margin:15px auto;">
         <el-col :xs="24" :sm="18" :md="18"  >
           <el-form :inline="true" :model="formInline" class="demo-form-inline" >
             <el-form-item label="时间" style="margin-bottom:0px;">
                <el-date-picker
                 v-model="formInline.date"
                 align="right"
                 unlink-panels
                 range-separator="至"
                 start-placeholder="开始日期"
                 end-placeholder="结束日期"
                 @change="dateChange"
                 style="width:160px"
                 >
                 <!-- :picker-options="pickerOptions" -->
               </el-date-picker>
             </el-form-item>
             <el-form-item  style="margin-bottom:0px;">
               <!-- <el-button type="primary" @click="onSubmit">查询</el-button> -->
               <el-button type="button" @click="zhou()">周</el-button>
               <!-- <el-button type="button" @click="yue()">月</el-button> -->
             </el-form-item>
           </el-form>
         </el-col>
         <el-col :xs="24" :sm="6" :md="6" >
           <el-switch 
             v-model="bgColor"
             active-text="浅色"
             inactive-text="深色"
             active-color="grey"
             inactive-color="#1f212d">
           </el-switch>
         </el-col>
      </el-row>
      <div id="showInfo"><div class="commColor"><div>时间</div><div>当前价</div><div>均价</div><div>涨幅</div><div>成交量</div></div></div>
      <el-row :gutter="20" :align="'middle'" class="info">
        <el-col :xs="24" :sm="24" :md="18"> 
          <div class="K-line" ref="klineChart"></div>
        </el-col>
         <el-col :xs="24" :sm="24" :md="6">
          <el-col :span="12">起始价：{{priceInfo.tradePriceBegin}}</el-col>
          <el-col :span="12">终止价：{{priceInfo.tradePriceEnd}}</el-col>
           <template>
            <el-table
              class="rightTable"
              :data="listData"
              size="mini"
              style="width: 100%">
              <el-table-column prop="type" label="类型">
                <template slot-scope="scope">{{scope.row.type=='buy'?'买'+(scope.row.id):'卖'+((scope.row.id-10))}}</template>
              </el-table-column>
              <el-table-column
                prop="unitPrice"
                label="单价">
              </el-table-column>
              <el-table-column
                prop="coinTotal"
                label="数量">
              </el-table-column>
            </el-table>
          </template>
        </el-col>
      </el-row>
    </div>
    <myfooter></myfooter>
  </div>
</template>

<script>
  import axios from 'axios'
  import mynav from "@/components/nav";
  import myfooter from "@/components/footer";
  import centerInfo from "@/components/centerinfo";
  import echarts from "echarts";
  import * as chartData from "../../assets/js/tmpData.js"
  import {initMOption} from "../../assets/js/k-line.js"
  import { trade, price, amount, tradeInfo,k_price} from '@/api/service'
  export default {
    mChart:null,
    opt:null,
    name: "home", 
    components: {
      mynav,
      myfooter,
      centerInfo
    },
  //  metaInfo: {
  //     title: 'This is the test',
  //     meta: [
  //       { charset: 'utf-8' },
  //       { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes' }
  //     ]
  //   },
    data() {
      return {
        bgColor:true,
        clearTime:null,
        formInline: {
          date: "",
        },
        priceInfo:{
           tradePriceBegin:'',
           tradePriceEnd:'',
        },
        listData:[],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [
          {
            text: '周',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          },
           {
            text: '月',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', date);
            }
          },
          {
            text: '季度',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 120);
              picker.$emit('pick', date);
            }
          },
          {
            text: '年度',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', date);
            }
          },
          ]
        }
      }
    },
    watch: {
         bgColor(val) {
            this.opt.backgroundColor=val?'#fff':"#1f212d";
            this.mChart.setOption(this.opt);
         }
       },
    created(){
     this.clearTime=setInterval(()=>{this.dateChange()},60*1000);
    },
    destroyed(){
      if(this.clearTime)clearInterval(this.clearTime);
    },
    mounted() {
      let ele = this.$refs.klineChart
      this.mChart = echarts.init(ele); 
      //最近十笔买卖 
      let ary=[];
      // trade({type:'sale'}).then(res=>ary=res.data); 
      // trade({type:'buy'}).then(res=>this.listData=ary.concat(res.data)); 
    axios.all([trade({type:'sale'}), trade({type:'buy'})]).then(axios.spread((sale, buy) =>{
          ary=sale.data
          this.listData=ary.concat(buy.data)
    }));


      tradeInfo().then(res=> this.priceInfo=res.data[0]);
      let beginTime=this.dateFormat(new Date(),'YYYY-mm-dd')+" 00:00:00";
      let endTime=this.dateFormat(new Date(),'YYYY-mm-dd')+" 23:59:59";
      this.search({beginTime,endTime});
    },
    methods: {
      zhou(){
        const date = new Date();
        let begin=date.getTime() - 3600 * 1000 * 24 * 7;
        let beginTime=this.dateFormat(new Date(begin));
        let endTime=this.dateFormat(date);
        this.search({beginTime,endTime});
      },
      yue(){
        const date = new Date();
        let begin=date.getTime() - 3600 * 1000 * 24 * 30;
        let beginTime=this.dateFormat(new Date(begin));
        let endTime=this.dateFormat(date);
        this.search({beginTime,endTime});
      },
      onSubmit() {
        this.search(this.dateFormat(this.formInline.date))
      },
      dateChange(){ 
        let beginTime=this.dateFormat(this.formInline.date,'YYYY-mm-dd')+" 00:00:00";
        let endTime=this.dateFormat(this.formInline.date,'YYYY-mm-dd')+" 23:59:59";
        this.search({beginTime,endTime});
      },
       search(date){
          // console.log(date);
           //时分图
          axios.all([ price(date), amount(date),k_price({type:'d',unit:'1',...date})]).then(axios.spread((priceRes, amountRes,dateprice)=>{
             let priceTime=[],unitPrice=[],avgPrice=[],amount=[],amountTime=[];
             let priceAry=priceRes.data;
             let amountAry=amountRes.data;
             for(let n=0;n<priceAry.length;n++){
               avgPrice.push(priceAry[n].avgPrice);
                unitPrice.push(priceAry[n].unitPrice);
                priceTime.push(priceAry[n].eventTime)
             }
            for(let m=0;m<amountAry.length;m++){
                amount.push(amountAry[m].volume);
                amountTime.push(amountAry[m].eventTime)
             }  
             this.opt=initMOption({priceTime,unitPrice,avgPrice,amount,amountTime,yestclose: dateprice.data[0].close},(args)=>{
                // console.log(args)
             });
            //  if(!this.opt){
            //   this.opt=initMOption({priceTime,unitPrice,avgPrice,amount,amountTime,yestclose: 33.01},'us');
            //  } else{
            //  this.opt.xAxis[0].data=priceTime;
            //  this.opt.xAxis[1].data=priceTime;
            //  this.opt.xAxis[2].data=amountTime;
            //  this.opt.series[0].data=unitPrice;
            //  this.opt.series[1].data=avgPrice;
            //  this.opt.series[2].data=amount;
            //  console.log(this.opt);
            //  }
             this.opt.backgroundColor = this.bgColor ? '#fff' : "#1f212d";
            this.mChart.setOption(this.opt);
          }));

      },
      dateFormat:(args,fm) =>{
      let fmt=fm||"YYYY-mm-dd HH:MM:SS"
      let ret;
      if(args){
        let  date=new Date(args)
           const opt = {
          "Y+": date.getFullYear().toString(),        // 年
          "m+": (date.getMonth() + 1).toString(),     // 月
          "d+": date.getDate().toString(),            // 日
          "H+": date.getHours().toString(),           // 时
          "M+": date.getMinutes().toString(),         // 分
          "S+": date.getSeconds().toString()          // 秒
      };
      for (let k in opt) {
          ret = new RegExp("(" + k + ")").exec(fmt);
          if (ret) {
              fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
          };
      };
      return fmt;
      }else{
        return "";
      }

  }
    }
  }
</script>

<style lang="less">
  .rightTable{
    .el-table__body{
       tr{
         line-height:15px;
          td{
            padding:0px;
            border-top:0px;

          }
          &:nth-child(odd){
            background:#dee2e6;
          }
          &:nth-child(even){
            background:#fff;
          }
        }
    }
  }
  .mynavContaier {
    background: #3740C3;
    width: 100%;
    height: 75px;
  }

  .kline {
    margin: 15px auto;
    text-align: left;
    width: 100%;
    height: calc(100vh - 75px);


    .buttonGroup {
      margin: 15px 0px;
    }

    .K-line {
      min-height:535px;
      width: 100%;
    }
  }
</style>
